//
//  UIButton+TS.swift
//  TSKit
//
//  Created by chenyusen on 2018/3/16.
//

import UIKit


// MARK: - 初始化
public extension UIButton {
    public convenience init(frame: CGRect = UIButton.appearance().frame,
                            title: String? = UIButton.appearance().currentTitle,
                            font: UIFont? = nil,
                            titleColor: UIColor? = nil,
                            backgroundColor: UIColor? = nil,
                            target:Any? = nil,
                            action:Selector? = nil) {
        
        self.init(frame: frame)
        
        if let title = title {
            setTitle(title, for: .normal)
        }
        
        if let font = font {
            titleLabel?.font = font
        }
        
        if let titleColor = titleColor {
            setTitleColor(titleColor, for: .normal)
        }
        
        if let backgroundColor = backgroundColor {
            setBackgroundColor(backgroundColor, for: .normal)
            if backgroundColor == .white {
                setBackgroundColor(UIColor(hex: 0xCECECE)!, for: .highlighted)
            }
        }
        if target != nil && action != nil {
            addTarget(target, action: action!, for: .touchUpInside)
        }
    }
}

// MARK: - 方法
public extension UIButton {
    
    /// 设置指定按钮点击状态下的背景色
    ///
    /// - Parameters:
    ///   - color: 颜色
    ///   - state: 状态
    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
        let colorImage = UIImage(color: color).stretchableImage(withLeftCapWidth: 1, topCapHeight: 1)
        setBackgroundImage(colorImage, for: state)
    }
}
